$(function () {
    //1.键盘事件
    keyClick()
    //2.初始请求页面
    init()
    //3.全选
    allCheck()
    //4.删除
    authorityDelete()
    //5.修改
    authorityUpdate()
    //6.增加
    authorityInsert()


})


//键盘事件
function keyClick() {
    $("#content").keyup(function () {
        var len = $(this).val().length;
        if (len > 299) {
            $(this).val($(this).val().substring(0, 300));
        }
        $("#word").text(len);
    });
    $("#admincontent").keyup(function () {
        var len = $(this).val().length;
        if (len > 299) {
            $(this).val($(this).val().substring(0, 300));
        }
        $("#adminword").text(len);
    });
}

//分页查询
function xianshi(num, page, data) {
    $('.listbody').children().remove()
    var page2 = (page - 1) * 10
    for (let i = 0; i < num; i++) {
        if (data[i + page2]) {
            var $str = $('<tr>' +
                '<td class="id">' + data[i + page2].id + '</td>' +
                '<td class="name">' + data[i + page2].name + '</td>' +
                '<td class="createTime">' + data[i + page2].createTime + '</td>' +
                '<td>' +
                '<div class="operation-btn">\n' +
                '<button type="button" class="btn btn-info" data-toggle="modal" data-target="#editmodal"><i class="fas fa-edit"></i> 编辑</button>\n' +
                '<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#delmodal"><i class="fas fa-eraser"></i> 删除</button>\n' +
                '</div>' +
                '</td>' +
                '<td class="content" style="display: none">' + data[i + page2].content + '</td>' +
                '</tr>')
            $('.listbody').append($str)
        }
    }

}


//页面数据初始化
function init() {
    $.ajax({
        url: '/authorityManage/getRole',
        type: 'Get',
        dataType: "json",
        processData: false,   // 不处理发送的数据
        contentType: false,   // 不设置Content-Type请求头
        success:
            function (res) {
                if (res.code !== 200) {
                    $.toast({
                        title: '通知',
                        subtitle: '1秒前',
                        content: '对不起，你没有权限',
                        type: 'success',
                        delay: 30000,
                        pause_on_hover: false
                    });
                    return;
                }
                var data = res.data
                console.log(data)
                xianshi(10, 1, data)
                var page = Math.ceil(data.length / 10)
                $('#pagination').pagination({
                    pageCount: page,
                    jump: true,
                    coping: true,
                    homePage: '首页',
                    endPage: '末页',
                    prevContent: '上页',
                    nextContent: '下页',
                    current: 1,  //当前第几页
                    callback: function (api) {
                        console.log(api.getCurrent())
                        xianshi(10, api.getCurrent(), data)
                    }
                })
            }
    })

}

//全选
function allCheck() {

    //新增模态框
    $(".adddataForm .all-click").change(function () {
        if ($(".all-click").is(":checked")) {


            $(".adddataForm input[name='permission']").attr("checked", true)
        } else {
            $(".adddataForm input[name='permission']").removeAttr("checked")

        }
    })
    //修改模态框
    $(".editdataForm .all-click").change(function () {
        if ($(".all-click").is(":checked")) {


            $(".editdataForm input[name='permission']").attr("checked", true)
        } else {
            $(".editdataForm input[name='permission']").removeAttr("checked")

        }
    })

}

//删除
function authorityDelete() {
    $(document).on("click", '.btn-danger', function () {
        // 获取tr层 方法1：
        var tr = $(this).closest("tr")
        var id = tr.find('.id').text()
        const index = Number(id)
        // const index = parseFloat(id)
        console.log(typeof index)
        $(".delebtn").off().click(function () {
            console.log("删除")
            $.ajax({
                // url: '/userManage/delete',
                // data:"id="+index,
                url: '/authorityManage/delete?id=' + id,
                type: 'Get',
                dataType: "json",
                // async: true,
                processData: false,   // 不处理发送的数据
                contentType: false,   // 不设置Content-Type请求头
                success: function (res) {
                    console.log(res)
                    if (res.code == 200) {
                        $.toast({
                            title: '通知',
                            subtitle: '5秒前',
                            content: res.data,
                            type: 'success',
                            delay: 3000,
                            pause_on_hover: false
                        });
                        $(this).parent().parent().parent().remove()
                    } else {
                        $.toast({
                            title: '通知',
                            subtitle: '5秒前',
                            content: res.msg,
                            type: 'error',
                            delay: 3000,
                            pause_on_hover: false
                        });
                    }
                }
            })
        })
        // 方法2


        // console.log($(this).parent().parent().parent().eq(0).text())
        // console.log($(this).parent().parent())
        // console.log($(this).parent().parent().text())
        // console.log($(this).parent().parent().eq(0).text())
        //
        // console.log(index)


    })
}

//增加
function authorityInsert() {
    $('.addbtn').off().on('click', function () {
        let AuthorityCreateVO = {};
        let RoleCreateVO = {}
        let PermissionVOList = []
        RoleCreateVO['name'] = $(".adddataForm input[name='name']").val()
        RoleCreateVO['content'] = $(".adddataForm textarea[name='content']").val()
        AuthorityCreateVO['roleCreateVO'] = RoleCreateVO

        for (var i = 0; i < $(".adddataForm .menu-item").length; i++) {
            var Permission = {}                            //权限对象
            var menuitem = $(".adddataForm .menu-item")[i]
            var menuName = $(menuitem).find("label.menu-name").text() //菜单名字
            var menuId = $(menuitem).find("label.menu-name").attr("value")//菜单id
            console.log(menuName)
            console.log(menuId)
            Permission["menuName"] = menuName
            Permission["id"] = menuId
            var authVOList = []
            for (var j = 0; j < $(menuitem).find("input[name='permission']:checked").length; j++) {
                var AuthVO = {}
                var authval = $(menuitem).find("input[name='permission']:checked")[j]
                AuthVO["authValue"] = $(authval).attr("value")
                AuthVO["authName"] = $(authval).attr("authName")
                authVOList.push(AuthVO)
                console.log(AuthVO["authValue"] + " " + AuthVO["authName"])
                console.log(authVOList)
            }
            Permission["authVOList"] = authVOList
            PermissionVOList.push(Permission)
        }
        AuthorityCreateVO["permissionVOList"] = PermissionVOList


        console.log(RoleCreateVO)
        $.ajax({
                url: '/authorityManage/insert',
                type: 'POST',
                dataType: "json",
                contentType: 'application/json;charset=UTF-8',
                async: true,
                data: JSON.stringify(
                    AuthorityCreateVO
                ),
                processData: false,   // 不处理发送的数据
                // contentType: false,   // 不设置Content-Type请求头
                success:
                    function (res) {
                        console.log(res)
                        if (res.code == 200) {
                            $.toast({
                                title: '通知',
                                subtitle: '5秒前',
                                content: res.data,
                                type: 'success',
                                delay: 1000,
                                pause_on_hover: false
                            });
                            window.location.href = '/authorityManage/index';
                        } else {
                            $.toast({
                                title: '通知',
                                subtitle: '5秒前',
                                content: res.msg,
                                type: 'error',
                                delay: 1000,
                                pause_on_hover: false
                            });
                        }
                    }
            }
        )
        return false;
    })
}

//修改
function authorityUpdate() {
    $(document).on('click', '.btn-info', function () {

        $('.editdataForm #active-left').addClass("active");
        $('.editdataForm #edit-basic').addClass("active");
        $('.editdataForm #active-right').removeClass("active");
        $('.editdataForm #edit-more').removeClass("active");
        let tr = $(this).closest("tr")
        let id = tr.find('.id').text()
        let name = tr.find('.name').text()
        let content = tr.find('.content').text()
        $(".editdataForm input[name='id']").val(id)
        $(".editdataForm input[name='name']").val(name)
        $(".editdataForm textarea[name='content']").val(content)
        $.ajax({
            url: '/authorityManage/getPrivateAuthority?id=' + id,
            type: 'Get',
            dataType: "json",
            // data: ,
            // async: true,
            processData: false,   // 不处理发送的数据
            contentType: false,   // 不设置Content-Type请求头
            success:
                function (res) {
                    var obj = res.data;
                    var oInput = $(".editdataForm input[name='permission']")
                    $(".editdataForm input[name='permission']").removeAttr("checked")
                    console.log(oInput)
                    $.each(obj, function (key, value) {
                        console.log(obj[key])

                        $.each(oInput, function (keys, values) {
                            if (oInput[keys].value == obj[key]) {
                                console.log(oInput[keys].value)
                                $(oInput[keys]).attr("checked", "checked");
                            }
                        })
                    })
                }
        })

        let UserManageUpdateVO = new FormData()

        $('.editbtn').off().on('click', function () {
            let AuthorityUpdateVO = {};
            let RoleUpdateVO = {}
            let PermissionVOList = []
            RoleUpdateVO['id'] = $(".editdataForm input[name='id']").val()
            RoleUpdateVO['name'] = $(".editdataForm input[name='name']").val()
            RoleUpdateVO['content'] = $(".editdataForm textarea[name='content']").val()
            AuthorityUpdateVO['roleUpdateVO'] = RoleUpdateVO

            for (var i = 0; i < $(".editdataForm .menu-item").length; i++) {
                var Permission = {}                            //权限对象
                var menuitem = $(".editdataForm .menu-item")[i]
                var menuName = $(menuitem).find("label.menu-name").text() //菜单名字
                var menuId = $(menuitem).find("label.menu-name").attr("value")//菜单id
                console.log(menuName)
                console.log(menuId)
                Permission["menuName"] = menuName
                Permission["id"] = menuId
                var authVOList = []
                for (var j = 0; j < $(menuitem).find("input[name='permission']:checked").length; j++) {
                    var AuthVO = {}
                    var authval = $(menuitem).find("input[name='permission']:checked")[j]
                    AuthVO["authValue"] = $(authval).attr("value")
                    AuthVO["authName"] = $(authval).attr("authName")
                    authVOList.push(AuthVO)
                    console.log(AuthVO["authValue"] + " " + AuthVO["authName"])
                    console.log(authVOList)
                }
                Permission["authVOList"] = authVOList
                PermissionVOList.push(Permission)
            }
            AuthorityUpdateVO["permissionVOList"] = PermissionVOList


            $.ajax({
                    url: '/authorityManage/update',
                    type: 'POST',
                    dataType: "json",
                    contentType: 'application/json;charset=UTF-8',
                    async: true,
                    data: JSON.stringify(
                        AuthorityUpdateVO
                    ),
                    processData: false,   // 不处理发送的数据
                    // contentType: false,   // 不设置Content-Type请求头
                    success:
                        function (res) {
                            console.log(res)
                            if (res.code == 200) {
                                $.toast({
                                    title: '通知',
                                    subtitle: '5秒前',
                                    content: res.data,
                                    type: 'success',
                                    delay: 1000,
                                    pause_on_hover: false
                                });
                                window.location.href = '/authorityManage/index';
                            } else {
                                $.toast({
                                    title: '通知',
                                    subtitle: '5秒前',
                                    content: res.msg,
                                    type: 'error',
                                    delay: 1000,
                                    pause_on_hover: false
                                });
                            }
                        }
                }
            )
            return false;
        })


    })
}